<template>
  <div id="app">
    <div>
      <span>姓名:</span>
      <input v-model.trim="username" type="text" />
    </div>
    <div>
      <span>年龄:</span>
      <input v-model.number="userage" type="number" />
    </div>
    <div>
      <span>性别:</span>
      <select v-model="usersix">
        <option value="男">男</option>
        <option value="女">女</option>
      </select>
    </div>
    <div>
      <button @click="add">添加/修改</button>
    </div>
    <div>
      <table border="1" cellpadding="10" cellspacing="0">
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
        <tr v-for="(item, index) in arr">
          <td>{{ item.id }}</td>
          <td>{{ item.name }}</td>
          <td>{{ item.age }}</td>
          <td>{{ item.six }}</td>
          <td>
            <button @click="del(index)">删除</button>
            <button @click="editor(index)">编辑</button>
          </td>
        </tr>
        <tfoot v-if="arr.length === 0">
          <div>表格已空</div>
        </tfoot>
      </table>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      arr: [
        {
          id: 1,
          name: "Tom",
          age: 19,
          six: "男",
        },
        {
          id: 2,
          name: "Jone",
          age: 21,
          six: "女",
        },
      ],
      username: "",
      userage: "",
      usersix: "男",
      isIndex: -1,
    };
  },
  methods: {
    add() {
      if (this.username.length === 0 || this.userage.length === 0)
        return alert("请输入非空白的姓名和年龄！");
      let id = this.arr.length === 0 ? 1 : this.arr[this.arr.length - 1].id;
      let obj = {
        id,
        name: this.username,
        age: this.userage,
        six: this.usersix,
      };
      console.log(this.isIndex);
      if (this.isIndex >= 0) {
        this.arr.splice(this.isIndex, 1, obj);
        this.isIndex = -1;
      } else {
        this.arr.push(obj);
      }
      this.username = "";
      this.userage = "";
    },
    del(index) {
      this.arr.splice(index, 1);
    },
    editor(index) {
      this.isIndex = index;
      this.username = this.arr[index].name;
      this.userage = this.arr[index].age;
      this.usersix = this.arr[index].six;
    },
  },
};
</script>